package com.hna.eking.AirlineServer.Utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.hna.eking.AirlineServer.Exception.RunServiceException;


@Component
public class FileUtils {
	private Logger logger = LoggerFactory.getLogger(FileUtils.class);
	@Value("${visualcharts.file.uploadpath}")
	private String MapFilePath;
	@Value("${visualcharts.state.area}")
	private String AREA_TYPE;
	
	/*生成上传文件名
	 * 参数：
	 * 	airportCode 航图编码
	 * file 上传文件
	 * mapType 航图类型
	 * */
	public String GenUploadFileName(String airportCode, String mapType, String FileOrgName) {
		String fileName = null;
		/*根据航图类型生成上传路径*/
        String realPath = MapFilePath;
        if(AREA_TYPE.equals(mapType)) {
        	realPath = realPath + "/common/";//得到文件上传目的位置的真实路径
        }else {
        	realPath = realPath + "/" + airportCode + "/";
        }
		/*创建上传目录*/
        File dir = new File(realPath);
        if(!dir.exists()){
        	if (!dir.mkdir())   //如果该目录不存在，就创建此抽象路径名指定的目录。
        		throw new RunServiceException(RunServiceException.FILE_UPLOAD_FAIL);
        }
        
        
        /*获取文件后缀*/
        String[] FileExtList = FileOrgName.split("\\.");
        int len = FileExtList.length;
        String prefix = UUID.randomUUID().toString();
        prefix = prefix.replace("-", "");
        String Ext =  null;
        
        if(len > 0) {
        	Ext = FileExtList[len - 1];
        	/*拼接文件名称*/
        	fileName = prefix + "." +Ext;
        }else {
        	fileName = prefix;
        }       	             
        
        return realPath + fileName;
	}
	/*上传航图用
	 * 参数：
	 * 	airportCode 航图编码
	 * file 上传文件
	 * mapType 航图类型
	 * */
	public void UploadFile(String FileName, MultipartFile file) throws  IllegalStateException,IOException{       	             
        /*上传文件*/
        File outFile =  new File(FileName);
        file.transferTo(outFile);
        
	}
	
	
	private int bufferSize = 4096;

	/*
	 * 根据文件列表打zip压缩包 
	 * 参数： 
	 * 文件列表：fileList 
	 * 目标文件：zipPath
	 * 
	 * 返回： 无
	 *
	 */
	public void compressFile(List<String> fileList, String zipPath) throws Exception {
		
		String ZipTmp = zipPath + "tmp";
		//创建zip输出流
        ZipOutputStream out = new ZipOutputStream( new FileOutputStream(ZipTmp));
        
        //创建缓冲输出流
        BufferedOutputStream bos = new BufferedOutputStream(out);
        
        for(int i = 0; i < fileList.size(); i++) {
        	//调用函数
            compress(out,bos, fileList.get(i));
        }
        
        bos.close();
        out.close();
        
        File fp = new File(ZipTmp);
        File fpTarget = new File(zipPath);
        fp.renameTo(fpTarget);
        logger.info("压缩完成");
	}

	private void compress(ZipOutputStream out, BufferedOutputStream bos,  String base) throws Exception {
		File sourceFile = new File(base);
		if(base == null || !sourceFile.exists()) {
			return;
		}
		byte[] buf = new byte[bufferSize];
		
		// 如果路径为目录（文件夹）
		if (sourceFile.isDirectory()) {

			// 取出文件夹中的文件（或子文件夹）
			File[] flist = sourceFile.listFiles();

			if (flist.length == 0)// 如果文件夹为空，则只需在目的地zip文件中写入一个目录进入点
			{
				out.putNextEntry(new ZipEntry(base + "/"));
			} else// 如果文件夹不为空，则递归调用compress，文件夹中的每一个文件（或文件夹）进行压缩
			{
				for (int i = 0; i < flist.length; i++) {
					compress(out, bos, base + "/" + flist[i].getName());
				}
			}
		} else// 如果不是目录（文件夹），即为文件，则先写入目录进入点，之后将文件写入zip文件中
		{
			out.putNextEntry(new ZipEntry(base));
			FileInputStream fos = new FileInputStream(sourceFile);
			BufferedInputStream bis = new BufferedInputStream(fos);

			int len = 0;
			// 将源文件写入到zip文件中
			while ((len = bis.read(buf)) != -1) {
				out.write(buf, 0, len);
			}
			out.closeEntry();
			bis.close();
			fos.close();
		}
	}
	
	public  void delete(String fileName) throws RunServiceException{
		if(fileName == null) {
        	return;
        }

		/*备份文件*/
		String BackFile = String.format("%s/backup/", MapFilePath);
		
		/*备份目录不存在*/
		File fp = new File(BackFile);
		if(!fp.exists()) {
			fp.mkdirs();
		}
		
		String[] OrgName = fileName.split("/");
		int size = OrgName.length;
		if(size > 0) {
			size -= 1;
		}
		String RealName = OrgName[size];
		
        File file = new File(fileName);
        if( !file.exists()) {
        	return;
        }
        /*移动文件*/
        file.renameTo(new File(BackFile +RealName));
        //file.delete();
       
    }
	
	

}
